# -*- coding:utf-8 -*-

'''

#使用例:

class States1(StateHandler):
    def _handling(self,path,contents):
        if States1.state==0:
            if path=="/":
                States1.state=1
                return "["+contents+"]"
        elif States1.state==1:
            if path=="/":
                States1.state=0
                return "[["+contents+"]]"
        return ""
    
    
ExecHTTPServer(States1)

'''

import BaseHTTPServer

#abstract
class StateHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    '''
    _handring(self,path,contents)を継承して使うこと.
    クラス変数stateも有効活用すべし
    '''
    state=0
    #override
    def do_POST(self):
        contents=self.rfile.read(int(self.headers["Content-Length"]))
        outputstr=self._handling(self.path,contents)
        self.wfile.write(outputstr)

    #override
    def do_GET(self):
        outputstr=self._handling(self.path,"")
        self.wfile.write(outputstr)
    
    def _handling(self,path,contents):
        raise NotImplementedError("override this method!!")
    
def ExecHTTPServer(StateHandleClass,host="localhost",port=8080):
    '''メインスレッドをブロックするので要注意
    
    StateHandlerをあらかじめ作って第1引数に入れてね

    #例:
    class States1(StateHandler):
    def _handling(self,path,contents):
        if States1.state==0:
            if path=="/":
                States1.state=1
                return "["+contents+"]"
        elif States1.state==1:
            if path=="/":
                States1.state=0
                return "[["+contents+"]]"
        return ""
    
    '''
    svr=BaseHTTPServer.HTTPServer((host,port),StateHandleClass)
    try:
        #svr.serve_forever()
        while True:
            svr.handle_request()
    except:
        svr.server_close()
        raise
        
if __name__=="__main__":
    #class States1(StateHandler):
        #def _handling(self,path,contents):
            #if States1.state==0:
                #if path=="/":
                    #States1.state=1
                    #return "["+contents+"]"
            #elif States1.state==1:
                #if path=="/":
                    #States1.state=0
                    #return "[["+contents+"]]"
            #return ""
        
        
    #ExecHTTPServer(States1)